package com.ruoyi.dishes.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ruoyi.dishes.domain.DishesType;
import com.ruoyi.dishes.service.IDishesTypeService;
import com.ruoyi.dishes.utils.IdWorker;
import com.ruoyi.dishes.utils.OssUtils;
import org.apache.http.entity.ContentType;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.dishes.domain.TbDishes;
import com.ruoyi.dishes.service.ITbDishesService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 菜品Controller
 * 
 * @author ruoyi
 * @date 2023-04-24
 */
@RestController
@RequestMapping("/dishes")
public class TbDishesController extends BaseController
{
    @Autowired
    private ITbDishesService tbDishesService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private OssUtils ossUtils;

    /**
     * 查询菜品列表
     */
    @RequiresPermissions("dishes:dishes:list")
    @GetMapping("/list/{page}/{size}")
    public AjaxResult list(TbDishes tbDishes,@PathVariable Integer page,@PathVariable Integer size) throws IOException {

        //创建查询请求
        SearchRequest request = new SearchRequest("dishes");
        BoolQueryBuilder query = QueryBuilders.boolQuery();

        //判断参数
        if(tbDishes.getDishesName()!=null && !tbDishes.getDishesName().equals("")){
         query.must(QueryBuilders.matchQuery("dishesName", tbDishes.getDishesName()));
        }

        if(tbDishes.getDishesTypeId()!=null && !tbDishes.getDishesTypeId().equals("")){
            query.must(QueryBuilders.termQuery("dishesTypeId", tbDishes.getDishesTypeId()));
        }


        if(tbDishes.getDishesPrice()!=null && !tbDishes.getDishesPrice().equals("")){
            query.must(QueryBuilders.termQuery("dishesPrice", tbDishes.getDishesPrice()));
        }

        //添加查询参数
        request.source().query(query);

        //设置高亮
        request.source().highlighter(new HighlightBuilder().field("dishesName"));
            //排序
        request.source().from((page-1)*size).size(size);

        //发送请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //获取总文档数量
        long total = response.getHits().getTotalHits().value;

        //获取所有文档,并遍历
        SearchHit[] hits = response.getHits().getHits();
        List<TbDishes> dishesArrayList = new ArrayList<>();
        for (SearchHit hit : hits) {
            //获取文档成字符串类型,并转换成对象
            String sourceAsString = hit.getSourceAsString();
            TbDishes dishes = JSON.parseObject(sourceAsString, TbDishes.class);
            //获取设置高亮的字段,并判断是否存在,存在则替换原字段
            HighlightField highlightField = hit.getHighlightFields().get("dishesName");
            if(highlightField!=null){
                String highName = highlightField.getFragments()[0].toString();
                dishes.setDishesName(highName);

            }

            dishesArrayList.add(dishes);
        }
        Map map=new HashMap();
        map.put("total", total);
        map.put("list", dishesArrayList);


//        startPage();
//        List<TbDishes> list = tbDishesService.selectTbDishesList(tbDishes);
//        return getDataTable(list);

        return AjaxResult.success(map);
    }

    /**
     * 导出菜品列表
     */
    @RequiresPermissions("dishes:dishes:export")
    @Log(title = "菜品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbDishes tbDishes)
    {
        List<TbDishes> list = tbDishesService.selectTbDishesList(tbDishes);
        ExcelUtil<TbDishes> util = new ExcelUtil<TbDishes>(TbDishes.class);
        util.exportExcel(response, list, "菜品数据");
    }

    /**
     * 获取菜品详细信息
     */
    @RequiresPermissions("dishes:dishes:query")
    @GetMapping(value = "/{dishesId}")
    public AjaxResult getInfo(@PathVariable("dishesId") Long dishesId)
    {
        return success(tbDishesService.selectTbDishesByDishesId(dishesId));
    }

    /**
     * 新增菜品
     */
    @RequiresPermissions("dishes:dishes:add")
    @Log(title = "菜品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbDishes tbDishes)
    {

        IdWorker idWorker = new IdWorker();
        tbDishes.setDishesId(idWorker.nextId());
        return toAjax(tbDishesService.insertTbDishes(tbDishes));
    }

    /**
     * 修改菜品
     */
    @RequiresPermissions("dishes:dishes:edit")
    @Log(title = "菜品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbDishes tbDishes)
    {
        return toAjax(tbDishesService.updateTbDishes(tbDishes));
    }

    /**
     * 删除菜品
     */
    @RequiresPermissions("dishes:dishes:remove")
    @Log(title = "菜品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{dishesIds}")
    public AjaxResult remove(@PathVariable Long[] dishesIds)
    {
        return toAjax(tbDishesService.deleteTbDishesByDishesIds(dishesIds));
    }

    @Autowired
    private IDishesTypeService dishesTypeService;

    /**
     * 查询所有菜品类型
     * @return
     */

    @RequiresPermissions("dishes:dishes:getDishesTypeList")
    @GetMapping("/getDishesTypeList")
    public AjaxResult getDishesTypeList(){
        List<DishesType> typeList = dishesTypeService.selectDishesTypeList(null);
        return AjaxResult.success(typeList);

    }




    /**
     * 全量同步
     * @return
     */
    @RequiresPermissions("dishes:dishes:handleEsTotal")
    @GetMapping("/handleEsTotal")
    public AjaxResult handleEsTotal() throws IOException {
       BulkRequest bulkRequest = new BulkRequest("dishes");
       List<TbDishes> dishesList = tbDishesService.selectTbDishesList(null);
       for (TbDishes dishes : dishesList) {
        IndexRequest request=   new IndexRequest("dishes").id(dishes.getDishesId().toString());

        request.source(JSON.toJSONString(dishes),XContentType.JSON);
        bulkRequest.add(request);
       }
       restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);

       return AjaxResult.success();

    }


    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //获取输入流
        InputStream inputStream = file.getInputStream();
        //读取文件信息
        BufferedImage image = ImageIO.read(inputStream);
        //文件宽高
        image.getHeight(null);
        image.getWidth(null);
        //创建画笔
        Graphics2D brush = image.createGraphics();
        //设置画笔颜色
        brush.setColor(Color.BLACK);
        //设置画笔样式
        brush.setFont(new Font("微软雅黑", Font.ITALIC, 100));
        //写上水印文字坐标
        brush.drawString("闪付", 30, 550);

        String tarImgPath="F:/imgs/"+originalFilename;


        // 将处理好的图片数据写入到新图片文件中
        FileOutputStream fs = new FileOutputStream(tarImgPath);
        ImageIO.write(image, "png", fs);

        fs.flush();;
        fs.close();
        inputStream.close();

        File fil = new File(tarImgPath);
        FileInputStream fileInputStream = new FileInputStream(fil);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(fil.getName(),originalFilename, ContentType.IMAGE_PNG.toString(), fileInputStream);

        String oneFiles = ossUtils.uploadOneFile(mockMultipartFile);

        return AjaxResult.success(oneFiles);
    }

}
